package com.hw.backapi.service.impl;
import java.time.LocalDateTime;
import java.util.Date;

import cn.hutool.json.JSONUtil;
import com.hw.backapi.context.UserAuthContext;
import com.hw.backapi.service.IAdminLogService;
import com.hw.common.exception.BaseException;
import com.hw.common.utils.ServletUtil;
import com.hw.model.dto.user.LoginDTO;
import com.hw.model.entity.AdminLogPO;
import com.hw.model.entity.AdminPO;
import com.hw.model.mapper.AdminLogMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 后台日志表 服务实现类
 * </p>
 *
 * @author 作者
 * @since 2023-03-07
 */
@Service
public class AdminLogServiceImpl extends ServiceImpl<AdminLogMapper, AdminLogPO> implements IAdminLogService {

    @Autowired
    UserAuthContext userAuthContext;

    @Override
    public void publishLog(String label, String param){
        AdminLogPO adminLog = this.getPublishLog(label, param);
        this.save(adminLog);
    }

    @Override
    public AdminLogPO getPublishLog(String label, String param) {
        HttpServletRequest request = ServletUtil.getRequest();
        AdminPO userInfo;
        try {

            userInfo = userAuthContext.getUserInfo();
        }catch (BaseException baseException){
            //只有登录接口会走这个异常
            userInfo = new AdminPO();
            userInfo.setUsername("登录接口");
            userInfo.setId(0L);
        }
        AdminLogPO adminLog = new AdminLogPO();
        adminLog.setLabel(label);
        adminLog.setIp(request.getRemoteAddr());
        adminLog.setPath(request.getRequestURL().toString());
        adminLog.setParam(param);
        adminLog.setLoginId(userInfo.getId());
        adminLog.setLoginName(userInfo.getUsername());
        adminLog.setCreatedAt(new Date());
        adminLog.setUpdatedAt(new Date());
        return adminLog;
    }
}
